using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Globalization;
using NLog;

namespace Barrage.Global
{
    /// <summary>
    /// A Config specialization for engine configuration data, such as screen resolution.
    /// </summary>
    public class EngineConfig: Config
    {
        /// <summary>
        /// Resolution Id
        /// </summary>
        public const string RESOLUTION = "Resolution";
        /// <summary>
        /// Fullscreen Id
        /// </summary>
        public const string FULLSCREEN = "Fullscreen";

        const string XML_ENGINECONFIG_ELEMENT = "EngineConfig";

        const string DEFAULT_RESOLUTION = "1024x768";
        const string DEFAULT_FULLSCREEN = "true";

        /// <summary>
        /// Fullscreen configuration value
        /// </summary>
        public bool FullScreen { get { return this[FULLSCREEN].Equals("true"); } }
        /// <summary>
        /// Width of selected resolution value
        /// </summary>
        public int ResolutionWidth { get { return int.Parse(this[RESOLUTION].Split('x')[0], NumberFormatInfo.InvariantInfo); } }
        /// <summary>
        /// Height of selected resolution value
        /// </summary>
        public int ResolutionHeight { get { return int.Parse(this[RESOLUTION].Split('x')[1], NumberFormatInfo.InvariantInfo); } }

        /// <summary>
        /// Loads the engine config from the specified file
        /// </summary>
        /// <param name="file">file name</param>
        public EngineConfig(string file):base(){
            XmlDocument d = new XmlDocument();
            try
            {
                d.Load(file);
                foreach (XmlNode n in d.ChildNodes)
                {
                    if (n.Name == XML_ENGINECONFIG_ELEMENT)
                    {
                        LoadXml(n.ChildNodes);
                        break;
                    }
                }
            }
            catch (Exception)
            {
                LogManager.GetLogger("EngineConfig").Warn("Configuration file not found. Loading defaults");
            }
            AddDefaultElements();            
        }

        void AddDefaultElements()
        {
            if (!Contains(RESOLUTION))
                Add(RESOLUTION, DEFAULT_RESOLUTION);
            if (!Contains(FULLSCREEN))
                Add(FULLSCREEN, DEFAULT_FULLSCREEN);
        }

        /// <summary>
        /// Saves the config to the specified file
        /// </summary>
        /// <param name="file">file name</param>
        public void Save(string file)
        {
            XmlDocument d = new XmlDocument();
            XmlElement xe = StoreConfig(d,XML_ENGINECONFIG_ELEMENT);
            d.AppendChild(xe);
            d.Save(file);
        }
    }
}
